from flask import Blueprint, jsonify, request, g
from app.err_no import errno_no
from loguru import logger
import json
import traceback
from app.db import dbUserManage
from app.db.mongoClient import MongoError
from app.globals.publicMethod import globalStrMd5

blueprint = Blueprint('user_manage', __name__, url_prefix='/api/user')


# @blueprint.route('/user_manage', methods=['POST'])
# def user_manage():
#     try:
#         j_data = json.loads(request.data)
#         return jsonify(errno_no.OK.data(None))
#     except Exception as e:
#         logger.error(f'errMsg:{str(e)},traceback={traceback.format_exc()}')
#         return jsonify(errno_no.ErrServerRuntime.data(None))

@blueprint.route('/v1/regedit', methods=['POST'])
def regedit():
    '''
    用户注册
    '''
    try:
        j_data = json.loads(request.data)
        userName = j_data.get('userName')
        userPwd = j_data.get('userPwd')
        userRealName = j_data.get('userRealName')
        userRoleId = j_data.get('userRoleId')
        userState = j_data.get('userState')
        userDesc = j_data.get('userDesc')
        RelationDiningNoList = j_data.get('RelationDiningNoList')
        RelationStallNo = j_data.get('RelationStallNo')
        # isalnum()判断是否数字和字母的组合 以下内容可以通过 '11'  'dd'   '1ddas'
        if userName is None or len(userName) <= 0  or userName.isalnum() is False\
                or userPwd is None or len(userPwd) <= 0 \
                or userRealName is None or len(userRealName) <= 0 or userRealName.isalnum() is False\
                or userRoleId is None or len(userRoleId) <= 0 \
                or userState is None or len(userState) <= 0 \
                or userDesc is None \
                or RelationDiningNoList is None or len(RelationDiningNoList) <= 0 \
                or RelationStallNo is None:
            return jsonify(errno_no.ErrServerParam.data(None))

        userPwd = globalStrMd5(userPwd)
        res = dbUserManage.regeditUser(userName, userPwd, userRealName, 
                    userRoleId, userState, userDesc, RelationDiningNoList, RelationStallNo, g.userId)

        if res is None:
            # 角色id不存在
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        if res is False:
            # 用户名已经存在
            return jsonify(errno_no.ErrServerDocumentExist.data(None))

        return jsonify(errno_no.OK.data({'userId': res}))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/edit', methods=['POST'])
def user_edit():
    '''
    编辑用户
    '''
    try:
        j_data = json.loads(request.data)
        userId = j_data.get('userId')
        userName = j_data.get('userName')
        userRealName = j_data.get('userRealName')
        userRoleId = j_data.get('userRoleId')
        userState = j_data.get('userState')
        userDesc = j_data.get('userDesc')
        RelationDiningNoList = j_data.get('RelationDiningNoList')
        RelationStallNo = j_data.get('RelationStallNo')
        if userId is None or len(userId) <= 0 \
                or userName is None or len(userName) <= 0 or userName.isalnum() is False\
                or userRealName is None or len(userRealName) <= 0 or userRealName.isalnum() is False\
                or userRoleId is None or len(userRoleId) <= 0 \
                or userState is None or len(userState) <= 0 \
                or userDesc is None \
                or RelationDiningNoList is None or len(RelationDiningNoList) <= 0 \
                or RelationStallNo is None:
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbUserManage.editUser(userId, userName, userRealName, 
                userRoleId, userState, userDesc, RelationDiningNoList, RelationStallNo, g.userId)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/del', methods=['POST'])
def user_del():
    '''
    删除用户
    '''
    try:      
        j_data = json.loads(request.data)
        userId = j_data.get('userId')
        if userId is None or len(userId) <= 0:
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbUserManage.delUser(userId)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        # 如果要删除超级管理员则不让操作
        if res is False:
            return jsonify(errno_no.ErrServerPermissionDenied.data(None))

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/edit_pwd', methods=['POST'])
def user_modify():
    '''
    修改密码
    '''
    try:
        j_data = json.loads(request.data)
        userId = j_data.get('userId')
        userPwdOld = j_data.get('userPwdOld')
        userPwdNew = j_data.get('userPwdNew')
        if userId is None or len(userId) <= 0 \
            or userPwdOld is None or userPwdOld.isalnum() is False\
            or userPwdNew is None or userPwdNew.isalnum() is False:
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbUserManage.modifyPwd(userId, userPwdNew, userPwdOld)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))
        # 旧密码不对
        if res is False:
            return jsonify(errno_no.ErrUserOrPwd.data(None))

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/reset_pwd', methods=['POST'])
def reset_pwd():
    '''
    重置其他用户密码
    '''
    try:
        # 如果不是超级管理员则无权限操作
        if g.userType != 'all':
            return jsonify(errno_no.ErrServerPermissionDenied.data(None))

        j_data = json.loads(request.data)
        userId = j_data.get('userId')
        userPwd = j_data.get('userPwd')
        if userId is None or len(userId) <= 0 \
            or userPwd is None or userPwd.isalnum() is False :
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbUserManage.resetPwd(userId, userPwd)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        # 如果要重置超级管理员密码则不让操作
        if res is False:
            return jsonify(errno_no.ErrServerPermissionDenied.data(None))

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))